import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class addfriend extends Dialog {

	protected Object result;
	protected Shell shell;
  protected ClientLogic logic;

	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public addfriend(Shell parent, int style) {
		super(parent, style);
		setText("Add Friend");
      logic = ClientLogic.getInstance();
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), getStyle());
		shell.setSize(400, 168);
		shell.setText(getText());
		
		Label lblUserName = new Label(shell, SWT.NONE);
		lblUserName.setBounds(10, 42, 85, 27);
		lblUserName.setText("User Name:");
		
		final Text text = new Text(shell, SWT.BORDER);
		text.setBounds(101, 36, 233, 27);
		
		final Label resultLabel = new Label(shell, SWT.NONE);
		resultLabel.setBounds(101, 69, 233, 17);
		resultLabel.setVisible(false);
		
		Button btnAdd = new Button(shell, SWT.NONE);
		btnAdd.setBounds(10, 99, 91, 29);
		btnAdd.setText("Add");
		btnAdd.addListener(SWT.Selection, new Listener() {
			public void handleEvent(org.eclipse.swt.widgets.Event event) {
				String newFriend = text.getText();
				if (newFriend.equals(logic.getUsername())) {
					resultLabel.setText("You can't add yourself as a friend.");
				} else if (!logic.isFriend(newFriend)) {
					if (logic.addFriend(newFriend)) {
						resultLabel.setText(newFriend + " has been added to your Friend's List.");
					} else {
						resultLabel.setText("This username doesn't exist.");
					}
				} else {
				resultLabel.setText("You are already friends with this user.");
				}
		        text.setText("");
		        resultLabel.setVisible(true);
			}
		});
		
		Button btnCancel = new Button(shell, SWT.NONE);
		btnCancel.setBounds(243, 99, 91, 29);
		btnCancel.setText("Close");
		btnCancel.addListener(SWT.Selection, new Listener() {
			public void handleEvent(org.eclipse.swt.widgets.Event event) {
				shell.close();
			}
		});

	}
}
